using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;
using AutoMapper;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 获取产品列表命令处理程序
    /// </summary>
    public class GetProductListCommandHandler : IRequestHandler<GetProductListCommand, ApiResult<PagingResult<List<ProductDto>>>>
    {
        private readonly MyDBContext _dbContext;
        private readonly IMapper _mapper;
        private readonly ILogger<GetProductListCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetProductListCommandHandler(MyDBContext dbContext, IMapper mapper, ILogger<GetProductListCommandHandler> logger)
        {
            _dbContext = dbContext;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取产品列表命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>产品列表分页结果</returns>
        public async Task<ApiResult<PagingResult<List<ProductDto>>>> Handle(GetProductListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询
                var query = _dbContext.Product.AsQueryable();

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    query = query.Where(p => p.ProductName.Contains(request.ProductName));
                }

                if (!string.IsNullOrEmpty(request.SKU))
                {
                    query = query.Where(p => p.SKU.Contains(request.SKU));
                }

                if (request.ProductTypeId.HasValue)
                {
                    query = query.Where(p => p.ProductTypeId == request.ProductTypeId.Value);
                }

                // 计算总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页查询
                var products = await query
                    .OrderByDescending(p => p.Id)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射为DTO
                var productDtos = _mapper.Map<List<ProductDto>>(products);

                // 构建分页结果
                var pagingResult = new PagingResult<List<ProductDto>>
                {
                    data = productDtos,
                    totalCount = totalCount,
                    totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize)
                };

                // 返回成功结果
                return new ApiResult<PagingResult<List<ProductDto>>>("获取产品列表成功")
                {
                    code = StatusCodeEnum.Ok,
                    data = pagingResult,
                    isSuc = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取产品列表失败");
                return new ApiResult<PagingResult<List<ProductDto>>>("获取产品列表失败：" + ex.Message)
                {
                    code = StatusCodeEnum.Fail,
                    isSuc = false
                };
            }
        }
    }
}
